package servlets;

import java.io.IOException;
import java.util.ArrayList;

import javax.servlet.ServletException;
import javax.servlet.http.HttpServlet;
import javax.servlet.http.HttpServletRequest;
import javax.servlet.http.HttpServletResponse;
import javax.servlet.http.HttpSession;

import controller.ItemController;
import model.Item;
import model.ShoppingCartItem;

public class AddToCartServlet extends HttpServlet {

	/**
	 * Constructor of the object.
	 */
	public AddToCartServlet() {
		super();
	}

	/**
	 * Destruction of the servlet. <br>
	 */
	public void destroy() {
		super.destroy(); // Just puts "destroy" string in log
		// Put your code here
	}

	public void doGet(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {

		doPost(request, response);
	}

	public void doPost(HttpServletRequest request, HttpServletResponse response)
			throws ServletException, IOException {
		String data = request.getParameter("data"); 
		HttpSession session = request.getSession();
		ArrayList<ShoppingCartItem> list = (ArrayList<ShoppingCartItem>) session.getAttribute("cart");
		
		if(data != null && !data.equals("")) {
			ArrayList<ShoppingCartItem> itemList = new ArrayList<ShoppingCartItem>();
			String[] record = data.split(";");
			for(String r : record) {
				String[] rd = r.split(":");
				Item item = ItemController.getItemById(rd[0]);
				ShoppingCartItem sItem = new ShoppingCartItem();
				sItem.setCategory(item.getCategory());
				sItem.setName(item.getName());
				sItem.setItemNumber(item.getItemNumber());
				sItem.setImagePath(item.getImagePath());
				sItem.setDescription(item.getDescription());
				sItem.setQuantity(rd[1]);
				sItem.setPrice(item.getPrice());
				itemList.add(sItem);
			}
			if (itemList.size() > 0) {			
				ArrayList<ShoppingCartItem> toBeAdded = new ArrayList<ShoppingCartItem>();
				if(list.size() > 0) {
					for(ShoppingCartItem i : itemList) {
						boolean isFound = false;
						for(ShoppingCartItem s : list) {
							if(i.getItemNumber() == s.getItemNumber()) {
								Integer a = Integer.parseInt(s.getQuantity());
								Integer b = Integer.parseInt(i.getQuantity());
								Integer t = a + b;
								s.setQuantity(t.toString());
								isFound = true;
								break;
							}	
							
						}
						if(!isFound) {
							toBeAdded.add(i);
						}
					}
					list.addAll(toBeAdded);
				} else {
					list.addAll(itemList);
				}
				session.setAttribute("cart", list);
				session.setAttribute("nbrOfItems", list.size());
			}
		}
		
		double totalPrice = 0;
		for(ShoppingCartItem i : list) {
			totalPrice += Integer.parseInt(i.getQuantity())*i.getPrice();
		}
		session.setAttribute("total", totalPrice);
		
		//Check how many items are there in the cart
		int nbrOfItems = 0;
		for (ShoppingCartItem i : list) {
			nbrOfItems += Integer.parseInt(i.getQuantity());
		}
		
		//Update session variable
		session.setAttribute("nbrOfItems", nbrOfItems);
		
		//Send it back to client side javascript
	    response.setContentType("text/plain");  
	    response.setCharacterEncoding("UTF-8"); 
	    response.getWriter().write("" + nbrOfItems); 
	}

	public void init() throws ServletException {
		// Put your code here
	}

}
